import SwiftUI
import SystemConfiguration.CaptiveNetwork
import CoreLocation
import CoreTelephony

class NetDataViewModel: NSObject, ObservableObject, CLLocationManagerDelegate {
    @Published var networkInfo: String = "正在获取网络信息..."
    private var locationManager: CLLocationManager?
    
    override init() {
        super.init()
        locationManager = CLLocationManager()
        locationManager?.delegate = self
        locationManager?.requestWhenInUseAuthorization() // 申请在使用时访问位置权限
        checkNetworkType()
    }
    
    func checkNetworkType() {
        if let ssid = fetchSSIDInfo() {
            networkInfo = "Wi-Fi: \(ssid)"
        } else if let carrierName = getCarrierName() {
            networkInfo = "运营商: \(carrierName)"
        } else {
            networkInfo = "无法获取网络信息"
        }
    }
    
    func fetchSSIDInfo() -> String? {
        if let interfaces = CNCopySupportedInterfaces() as? [String] {
            for interface in interfaces {
                if let interfaceInfo = CNCopyCurrentNetworkInfo(interface as CFString) as NSDictionary? {
                    return interfaceInfo[kCNNetworkInfoKeySSID as String] as? String
                }
            }
        }
        return nil
    }
    
    func getCarrierName() -> String? {
        let networkInfo = CTTelephonyNetworkInfo()
        if let carrier = networkInfo.subscriberCellularProvider {
            return carrier.carrierName
        }
        return nil
    }
    
    func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
        if status == .authorizedWhenInUse || status == .authorizedAlways {
            checkNetworkType()
        } else {
            networkInfo = "未授权访问位置信息"
        }
    }
}
